import threading

import cv2
import os
import socket
from paddleocr import PaddleOCR, draw_ocr


def delay(s, status):
    while True:
        status = s.recv(1024).decode('utf-8')
        if status:
            print(status)
            break


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
s.connect(('127.0.0.1', 9995))
status = s.recv(1024).decode('utf-8')
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
boxes = []
txts = []
scores = []
x = []
cap = cv2.VideoCapture(0)
u = 0

freq = 10
while True:
    u += 1
    img = cap.grab()
    if not img:
        break

    if u % freq == 1:
        success, img = cap.retrieve()
        if img is None:
            break

        result = ocr.ocr(img, cls=True)
        im_show = img
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                delays = 0
                boxes = [line[0] for line in res]
                txts = [line[1][0] for line in res]
                scores = [line[1][1] for line in res]
                if status and (txts is not None) and (scores is not None):
                    ts = 0
                    for score in scores:
                        if score > 0.85:
                            print("+++++++++++", txts, scores)
                            s.send(bytes(txts[ts], encoding="utf8"))
                            ts += 1
                            # status = s.recv(1024).decode('utf-8')
                            status = False
                            # t = threading.Thread(target=delay, args=(s, status,))
                            # t.start()
                            status = s.recv(1024).decode('utf-8')
                            while 1:
                                if status:
                                    break
                            print(status)
                im_show = draw_ocr(img, boxes, txts, scores, font_path='./datasets/ppocr_img/fonts/simfang.ttf')
                txts = []
                scores = []

        cv2.imshow("img", im_show)
        k = cv2.waitKey(1)
        if k == 27:
            cv2.destroyAllWindows()
            break
        elif k == ord("s"):
            cv2.imwrite("image2.jpg", im_show)
            cv2.destroyAllWindows()
            break
s.close()
cap.release()
